import cv2
import numpy as np
import time

# 1. 加载图像
image = cv2.imread('/home/JSDC/017254/code/gitee/map_learing/map_grid/04_xyzrpy_visual/demo/mask_0_0.png', cv2.IMREAD_GRAYSCALE)
if image is None:
    print("Failed to load image.")
    exit()

# 2. 二值化图像（如果需要）
_, binary_image = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY)

# 3. 提取轮廓
contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 4. 创建一个显示图像
contour_image = np.zeros((image.shape[0], image.shape[1], 3), dtype=np.uint8)

# 5. 绘制轮廓
cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2)

# 6. 显示结果

cv2.imwrite("find_contor_Bus.jpg", contour_image)




min_y  = 10000

# 5. 计算并绘制凸包
for i, contour in enumerate(contours):
    hull = cv2.convexHull(contour)
    # 打印凸包的点
    print(f"Contour {i} Convex Hull Points:")
    for point in hull:
        print(point[0])  # 打印每个点的坐标
        if min_y < point[0][1]:
            min_y  = point[0][1]
    cv2.drawContours(contour_image, [hull], -1, (0, 255, 0), 2)


print(f'min_y {min_y}')

# 6. 显示结果
# cv2.imshow('Convex Hull', contour_image)
cv2.imwrite("convex_hll_bus.jpg", contour_image)

# cv2.imshow('Contours', contour_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


# 4. 创建一个显示图像
contour_image1 = np.zeros((image.shape[0], image.shape[1], 3), dtype=np.uint8)



#######################
#  多边形拟合过程
#######################

approxs = []
# 5. 多边形拟合轮廓
for contour in contours:
    start_time = time.time()
    # 计算轮廓的周长
    epsilon = 0.02 * cv2.arcLength(contour, True)

    print(epsilon)
    # 使用多边形拟合轮廓
    approx = cv2.approxPolyDP(contour, epsilon, True)
    # 结束计时
    end_time = time.time()

    # 计算耗时
    execution_time = end_time - start_time
    print(f"代码执行耗时: {execution_time:.4f} 秒")
    approxs.append(approx)

    print("轮廓点:")
    # for point in approx:
    #     print(point[0])
    print(f'len: {approx.__len__()}')
    
    # 绘制拟合的多边形
    cv2.drawContours(contour_image1, [approx], -1, (0, 255, 0), 2)
    # for point in approx:
    #     print(point[0])
cv2.imwrite('polygon_approximation_bus.png', contour_image1)
